package com.example.handlerdemo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ThreadActivity extends AppCompatActivity {
    private static final String TAG = "ThreadActivity";
    private Button btn;
    private Handler mHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refresh);
        btn = (Button) findViewById(R.id.btn);
        // 开启一个子线程，去创建Handler
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "run: , thread name: " + Thread.currentThread().getName());
                Looper.prepare();
                // 创建Handler传入主线程的Looper
                mHandler = new Handler(Looper.getMainLooper()){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.e(TAG, "handleMessage, thread name: " + Thread.currentThread().getName());
                    }
                };
                Looper.loop();
            }
        }).start();

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onCreate: time:" + SystemClock.uptimeMillis() / 1000.0);
                // 发送一个消息
                //mHandler.sendEmptyMessage(100);
            }
        });
    }
}
